<template>
  <div class="p-2">
    <el-row :gutter="20">
      <!-- 部门树 -->
      <el-col :lg="4" :xs="24" style="">
        <TreeLeft :dictType="'wms_product_service'" v-model:dict-value="pd.queryParams.treeValue"
                  style="width: 200px;margin-top: 8px"/>
      </el-col>
      <el-col :lg="20" :xs="24">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                    :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div class="search" v-show="pd.showSearch">
            <el-form :model="pd.queryParams" ref="queryFormRef" :inline="true" label-width="68px">
              <el-form-item label="产品编码" prop="sku">
                <el-input v-model="pd.queryParams.sku" placeholder="请输入产品编码" clearable style="width: 240px"
                          @keyup.enter="handleQuery"/>
              </el-form-item>
              <el-form-item label="产品名称" prop="name">
                <el-input v-model="pd.queryParams.name" placeholder="请输入产品名称" clearable style="width: 240px"
                          @keyup.enter="handleQuery"/>
              </el-form-item>
              <el-form-item label="产品规格" prop="specification">
                <el-input v-model="pd.queryParams.specification" placeholder="请输入产品规格" clearable style="width: 240px"
                          @keyup.enter="handleQuery"/>
              </el-form-item>
              <el-form-item label="更新时间" style="width: 308px">
                <el-date-picker
                  v-model="dateRangeUpdateTime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </transition>
        <el-card shadow="never">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['wms:product:add']">新增
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="pd.single" @click="handleUpdate()"
                           v-hasPermi="['wms:product:edit']">修改
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="pd.multiple" @click="handleDelete()"
                           v-hasPermi="['wms:product:remove']">删除
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport"
                           v-hasPermi="['wms:product:export']">导出
                </el-button>
              </el-col>
              <right-toolbar v-model:showSearch="pd.showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table v-loading="pd.loading" :data="pd.productList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="产品子id" align="center" prop="id" v-if="true"/>
            <el-table-column label="产品编码" align="center" prop="sku"/>
            <el-table-column label="产品名称" align="center" prop="name"/>
            <el-table-column label="产品规格" align="center" prop="specification"/>
            <el-table-column label="包装单位" align="center" prop="packingUnit"/>
            <el-table-column label="计量单位" align="center" prop="measureUnit"/>
            <el-table-column label="包装数量" align="center" prop="packingQuantity"/>
            <el-table-column label="销售价格" align="center" prop="price"/>
            <el-table-column label="采购价格" align="center" prop="purchasePrice"/>
            <el-table-column label="类别" align="center" prop="treeValue">
              <template #default="scope">
                <dictTag :options="wms_product_service" :value="scope.row.treeValue"/>
              </template>
            </el-table-column>
            <el-table-column label="产品属性" align="center" prop="attrValue"/>
            <el-table-column label="产品状态" align="center" prop="status">
              <template #default="scope">
                <dict-tag :options="fms_bill_status" :value="scope.row.status"/>
              </template>
            </el-table-column>
            <el-table-column label="是否库存" align="center" prop="isStock">
              <template #default="scope">
                <dict-tag :options="sys_yes_no" :value="scope.row.isStock"/>
              </template>
            </el-table-column>
            <el-table-column label="可否销售" align="center" prop="isSales">
              <template #default="scope">
                <dict-tag :options="sys_yes_no" :value="scope.row.isSales"/>
              </template>
            </el-table-column>
            <el-table-column label="可否采购" align="center" prop="isPurchase">
              <template #default="scope">
                <dict-tag :options="sys_yes_no" :value="scope.row.isPurchase"/>
              </template>
            </el-table-column>
            <el-table-column label="可否生产" align="center" prop="isProduce">
              <template #default="scope">
                <dict-tag :options="sys_yes_no" :value="scope.row.isProduce"/>
              </template>
            </el-table-column>
            <el-table-column label="是否物料" align="center" prop="isMaterial">
              <template #default="scope">
                <dict-tag :options="sys_yes_no" :value="scope.row.isMaterial"/>
              </template>
            </el-table-column>
            <el-table-column label="委外加工" align="center" prop="isOutsource">
              <template #default="scope">
                <dict-tag :options="sys_yes_no" :value="scope.row.isOutsource"/>
              </template>
            </el-table-column>
            <el-table-column label="最低库存" align="center" prop="minStock"/>
            <el-table-column label="最大库存" align="center" prop="maxStock"/>
            <el-table-column label="备注" align="center" prop="remark"/>
            <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-tooltip content="修改" placement="top">
                  <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                             v-hasPermi="['wms:product:edit']"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                             v-hasPermi="['wms:product:remove']"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="pd.total>0" :total="pd.total" v-model:page="pd.queryParams.pageNum"
                      v-model:limit="pd.queryParams.pageSize" @pagination="getList"/>
        </el-card>
        <!-- 添加或修改物料产品对话框 -->
        <el-dialog :title="pd.dialog.title" v-model="pd.dialog.visible" width="500px" append-to-body>
          <el-form ref="productFormRef" :model="pd.form" :rules="pd.rules" label-width="80px">
            <el-form-item label="产品编码" prop="sku">
              <el-input v-model="pd.form.sku" placeholder="请输入产品编码"/>
            </el-form-item>
            <el-form-item label="产品名称" prop="name">
              <el-input v-model="pd.form.name" placeholder="请输入产品名称"/>
            </el-form-item>
            <el-form-item label="产品规格" prop="specification">
              <el-input v-model="pd.form.specification" placeholder="请输入产品规格"/>
            </el-form-item>
            <el-form-item label="包装单位" prop="packingUnit">
              <el-input v-model="pd.form.packingUnit" placeholder="请输入包装单位"/>
            </el-form-item>
            <el-form-item label="计次单位" prop="measureUnit">
              <el-input v-model="pd.form.measureUnit" placeholder="请输入计量单位"/>
            </el-form-item>
            <el-form-item label="包装数量" prop="packingQuantity">
              <el-input v-model="pd.form.packingQuantity" placeholder="请输入包装数量"/>
            </el-form-item>
            <el-form-item label="销售价格" prop="price">
              <el-input v-model="pd.form.price" placeholder="请输入销售价格"/>
            </el-form-item>
            <el-form-item label="采购价格" prop="purchasePrice">
              <el-input v-model="pd.form.purchasePrice" placeholder="请输入采购价格"/>
            </el-form-item>
            <el-form-item label="产品树" prop="treeValue">
              <TreeSelect :dictType="'wms_product_service'" v-model:dictValue="pd.form.treeValue" placeholder="请选择产品树"/>
            </el-form-item>
            <el-form-item label="产品属性" prop="attrValue">
              <el-input v-model="pd.form.attrValue" placeholder="请输入产品属性"/>
            </el-form-item>
            <el-form-item label="产品状态" prop="status">
              <el-select v-model="pd.form.status" placeholder="请选择产品状态">
                <el-option v-for="dict in fms_bill_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="可否销售" prop="isSales">
              <el-radio-group v-model="pd.form.isSales">
                <el-radio v-for="dict in sys_yes_no" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="pd.form.remark" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button :loading="pd.buttonLoading" type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </template>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="Product" lang="ts">
import {addProduct, delProduct, getProduct, listProduct, updateProduct} from '@/api/wms/product';
import {ProductForm, ProductQuery, ProductVO} from '@/api/wms/product/types';
import TreeLeft from '@/views/system/dict/treeLeft.vue';
import TreeSelect from '@/views/system/dict/treeSelect.vue';

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const {
  wms_product_service,
  fms_bill_status,
  sys_yes_no
} = toRefs<any>(proxy?.useDict('wms_product_service', 'fms_bill_status', 'sys_yes_no'));


const dateRangeUpdateTime = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const productFormRef = ref<ElFormInstance>();

const initFormData: ProductForm = {
  id: undefined,
  sku: undefined,
  name: undefined,
  specification: undefined,
  packingUnit: undefined,
  measureUnit: undefined,
  packingQuantity: undefined,
  price: undefined,
  purchasePrice: undefined,
  treeValue: undefined,
  attrValue: undefined,
  status: undefined,
  isStock: undefined,
  isSales: undefined,
  isPurchase: undefined,
  isProduce: undefined,
  isMaterial: undefined,
  isOutsource: undefined,
  minStock: undefined,
  maxStock: undefined,
  remark: undefined
}
const pd = reactive({
  productList: <ProductVO[]>([]),
  buttonLoading: false,
  loading: true,
  showSearch: true,
  ids: <Array<string | number>>([]),
  single: true,
  multiple: true,
  total: 0,
  form: <ProductForm>{...initFormData},
  queryParams: <ProductQuery>{
    pageNum: 1,
    pageSize: 10,
    sku: undefined,
    name: undefined,
    specification: undefined,
    treeValue: undefined,
    isStock: undefined,
    params: {
      updateTime: undefined,
    }
  },
  rules: <ElFormRules>{
    sku: [
      {required: true, message: "产品编码不能为空", trigger: "blur"}
    ],
    name: [
      {required: true, message: "产品名称不能为空", trigger: "blur"}
    ],
    specification: [
      {required: true, message: "产品规格不能为空", trigger: "blur"}
    ],
    packingUnit: [
      {required: true, message: "包装单位不能为空", trigger: "blur"}
    ],
    measureUnit: [
      {required: true, message: "计量单位不能为空", trigger: "blur"}
    ],
    packingQuantity: [
      {required: true, message: "包装数量不能为空", trigger: "blur"}
    ],
    price: [
      {required: true, message: "销售价格不能为空", trigger: "blur"}
    ],
    purchasePrice: [
      {required: true, message: "采购价格不能为空", trigger: "blur"}
    ],
    treeValue: [
      {required: true, message: "类别不能为空", trigger: "change"}
    ],
    status: [
      {required: true, message: "产品状态不能为空", trigger: "change"}
    ],
    isStock: [
      {required: true, message: "是否库存不能为空", trigger: "change"}
    ],
    isSales: [
      {required: true, message: "可否销售不能为空", trigger: "change"}
    ]
  },
  dialog: <DialogOption>{
    visible: false,
    title: ''
  }
});

// const { queryParams, form, rules } = toRefs(data);

/** 查询物料产品列表 */
async function getList() {
  pd.loading = true;
  pd.queryParams.params = {};
  proxy?.addDateRange(pd.queryParams, dateRangeUpdateTime.value, 'UpdateTime');
  const res = await listProduct(pd.queryParams);
  pd.productList = res.rows;
  pd.total = res.total;
  pd.loading = false;
}

/** 取消按钮 */
function cancel() {
  reset();
  pd.dialog.visible = false;
}

/** 表单重置 */
function reset() {
  pd.form = {...initFormData};
  productFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  pd.queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRangeUpdateTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: ProductVO[]) {
  pd.ids = selection.map(item => item.id);
  pd.single = selection.length != 1;
  pd.multiple = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  pd.dialog.visible = true;
  pd.dialog.title = "添加物料产品";
}

/** 修改按钮操作 */
async function handleUpdate(row?: ProductVO) {
  reset();
  const _id = row?.id || pd.ids[0]
  const res = await getProduct(_id);
  Object.assign(pd.form, res.data);
  pd.dialog.visible = true;
  pd.dialog.title = "修改物料产品";
}

/** 提交按钮 */
function submitForm() {
  productFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      pd.buttonLoading = true;
      if (pd.form.id) {
        await updateProduct(pd.form).finally(() => pd.buttonLoading = false);
      } else {
        await addProduct(pd.form).finally(() => pd.buttonLoading = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      pd.dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
async function handleDelete(row?: ProductVO) {
  const _ids = row?.id || pd.ids;
  await proxy?.$modal.confirm('是否确认删除服务产品编号为"' + _ids + '"的数据项？').finally(() => pd.loading = false);
  await delProduct(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
function handleExport() {
  proxy?.download('wms/product/export', {
    ...pd.queryParams
  }, `product_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
